C实例----IP地址转换(二进制转十进制,malloc实现)

特别说明:这里malloc没有用free回收是因为这边的环境是Xcode,加上free提示已经回收错误,故没有回收内存。
代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* 去除字符串里所有的空格 */
char *DeleteBlank(char *src);

int main ()
{
    char *address;
    int *add, *pos, i;

    if ((address = (char *)malloc(50 * sizeof(char))) == NULL) //防止手残多输入空格
    {
        printf("malloc fail!\n");
        exit(1);
    }
    memset(address, 0, 50);

    if ((add = (int *)malloc(4 * sizeof(int))) == NULL)
    {
        printf("malloc fail!\n");
        exit(2);
    }
    memset(add, 0, 4);

    pos = add;
    printf("Please input binary adress 32 bits (sample : 11111111 11111111 11111111 00000000): \n");
    scanf("%[^\n]",address);

    memcpy(address, DeleteBlank(address), 32);

    address = (char *)realloc(address, 32 * sizeof(char));

    for (i = 0; i < 32; i ++)
    {
        *add = (*add) * 2 + (*address++ - '0');
        if (i > 1 && (i + 1) % 8 == 0)
            add ++;
    }

    printf("IP : %d.%d.%d.%d\n", *(pos), *(pos+1), *(pos+2), *(pos+3));

    return 0;
}

char *DeleteBlank(char *src)
{
    char *p = src;
    int i,j;
    for(i=0;src[i];i++)
    {
        if(src[i]==' ')
        {
            for(j = i; src[j]; j++)
                src[j] = src[j+1];
            i--;
        }
    }
    return p;
}

运行结果:
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值